package session

import (
	"net/http"
	"project/study-go/config"
	"project/study-go/db"
	"project/study-go/ecode"
	"project/study-go/logger"

	"github.com/boj/redistore"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/sessions"
)

var (
	//SStore 全局 session 存储器
	SStore *redistore.RediStore
)

func Init() {
	var (
		err error
	)
	SStore, err = redistore.NewRediStoreWithPool(db.RedisPool, []byte(config.Vip.GetString("session.authkey")))
	if err != nil {
		logger.RoutineLogger.Errorf("create session redistore error,please check.")
	}
	logger.RoutineLogger.Infof("create session redistore success.")
	SStore.SetMaxAge(config.Vip.GetInt("session.MaxAge"))
}

//SetSession 得到并存储session信息
func SetSession(c *gin.Context, name string, data map[interface{}]interface{}) error {
	sess, err := SStore.Get(c.Request, name)
	if err != nil {
		logger.UnexpectLogger.Errorf("Get session By name:%s ; error: %s", name, err)
		return ecode.ErrInternalError
	}
	sess.Values = data
	err = sess.Save(c.Request, c.Writer)
	if err != nil {
		logger.UnexpectLogger.Errorf("Save session By name:%s ; error: %s", name, err)
		return ecode.ErrInternalError
	}
	return nil
}

//DeleteSession 通过 session name 删除session
func DeleteSession(c *gin.Context, name string) error {
	sess, err := SStore.Get(c.Request, name)
	if err != nil {
		logger.UnexpectLogger.Errorf("Get session By name:%s ; error: %s", name, err)
		return ecode.ErrInternalError
	}

	sess.Options.MaxAge = -1
	if err = sess.Save(c.Request, c.Writer); err != nil {
		logger.UnexpectLogger.Errorf("delete session By name:%s ; error: %s", name, err)
		return ecode.ErrInternalError
	}

	return nil
}

//GetSession 拿到通过 sessionName 拿到 session
func GetSession(r *http.Request, name string) (*sessions.Session, error) {
	session, err := SStore.Get(r, name)
	return session, err
}
